package tsing.javase.list.list_learn;

import tsing.good_simple.goodutil.ListUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Date 2024/11/25 10:50
 * @Author Tsing
 * ArrayList 集合缩容
 *
 * ArrayList不支持自动缩容，但是提供了一个trimToSize()方法，来实现缩容的功能
 */
public class ArrayListResizeExample {

    public final static  int INIT_CAPACITY = 5;


    public final static int ADD_CAPACITY = 10;


    public final static int REMOVED_CAPACITY = 3;


    public static void main(String[] args) throws  Exception {

        ArrayList<Integer> list = new ArrayList<>(INIT_CAPACITY);
        System.out.println("initial capacity :"+ ListUtils.getListCapacity(list)   +"\t length:"+list.size());

        for (int i = 1; i <= ADD_CAPACITY; i++) {
            list.add(i);
        }
        System.out.println("after added capacity :"+ ListUtils.getListCapacity(list)   +"\t length:"+list.size());


        Iterator<Integer> iterator = list.iterator();
        for (int i = 0; i < REMOVED_CAPACITY && iterator.hasNext(); i++) {
            iterator.next();
            iterator.remove();

        }

        // trimToSize():将集合的容量改变成集合中元素的长度 ，底层是copyOf方法，复制一个集合，再将元素放进去
        list.trimToSize();


        System.out.println("after reduced capacity :"+ ListUtils.getListCapacity(list)   +"\t length:"+list.size());
    }





}
